package com.guodi.model.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.core.tool.utils.CollectionUtil;
import com.guodi.core.tool.utils.Func;
import com.guodi.map.entity.MapDivision;
import com.guodi.model.dto.IdtEstimateResultDto;
import com.guodi.model.entity.*;
import com.guodi.model.enums.CmeReportIdtDescribeEnum;
import com.guodi.model.mapper.IdtIndicatorsDirMapper;
import com.guodi.model.mapper.IdtIndicatorsTypeMapper;
import com.guodi.model.service.IIdtIndicatorsDirService;
import com.guodi.model.service.IIdtIndicatorsService;
import com.guodi.model.service.IIdtIndicatorsTypeService;
import com.guodi.model.service.IIdtMonitorValueService;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @描述：指标目录表 服务类
 * @作者: 彭辉
 * @日期: 2020-06-05
 */
@Service
public class IdtIndicatorsDirServiceImpl extends ServiceImpl<IdtIndicatorsDirMapper, IdtIndicatorsDir> implements IIdtIndicatorsDirService {

    @Resource
    private IdtIndicatorsDirMapper idtIndicatorsDirMapper;
    @Resource
    private IdtIndicatorsTypeMapper idtIndicatorsTypeMapper;

    @Resource
    private IIdtIndicatorsService iIdtIndicatorsService;

    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;

    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;

    //默认指标体系编码
    public static String MONITOR_WARNING_CODE = "monitor-warning";

    /***
     * @描述: 获取上报值填报时用的指标列表，会过滤非当前用户可见的指标，只能看责任单位是自己单位或子单位的指标
     * @入参: idtTypeCode 指标体系编码，非空必填
     * @入参: orgId 组织单位id，如果不为空，则只返回责任单位为该单位及其子单位的指标
     * @入参: idtType 指标类型，不为空时会过滤指标
     * @入参: keyWord 关键词，不为空时会根据指标名和指标编号过滤，
     * @入参: idtStatus 指标状态，不为空时过滤
     * @出参: 指标列表
     * @作者: 陈宏成
     */
    @Override
    public List<ApiIdtIndicatorsDir> listIdtDirForReport(String idtTypeCode, String orgId, String idtType, String keyWord, String idtStatus, String divisionCode, String idtTypeId) {
        List<ApiIdtIndicatorsDir> idtDirList = null;
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.getById(idtTypeId);
        if (null == one) {
            return new LinkedList<>();
        }
        // 查询指标
        idtDirList = this.listDirByCode(one.getId(), null, null);
        // 根据关键词过滤
        if (StringUtils.isNotBlank(keyWord)) {
            idtDirList = idtDirList.stream().filter(idtDir -> {
                // 如果是指标，并且名字或者编码包含关键词，就保留，其余删除；如果是目录，直接返回
                return idtDir.getType() == 1 || (idtDir.getType() == 2 && (idtDir.getName().contains(keyWord) || idtDir.getIdtCode().contains(keyWord)));
            }).collect(Collectors.toList());
        }
        // 根据指标类型过滤
        if (StringUtils.isNotBlank(idtType)) {
            idtDirList = idtDirList.stream().filter(idtDir -> {
                // 如果是指标，并且指标类型和指定的一致，就保留，其余删除；如果是目录，直接返回
                return idtDir.getType() == 1 || (idtDir.getType() == 2 && idtDir.getIdtType().equals(idtType));
            }).collect(Collectors.toList());
        }
        // 根据指标状态过滤
        if (StringUtils.isNotBlank(idtStatus)) {
            idtDirList = idtDirList.stream().filter(idtDir -> {
                // 如果是指标，并且指标类型和指定的一致，就保留，其余删除；如果是目录，直接返回
                return idtDir.getType() == 1 || (idtDir.getType() == 2 && idtDir.getIdtIndicators() != null && idtDir.getIdtIndicators().getUpdateReportStatus().equals(idtStatus));
            }).collect(Collectors.toList());
        }
        // 2021-09-29 去除限制，所有人见到的数据都是一样的
//        // 过滤非当前用户可见的指标，只能看责任单位是自己单位或子单位的指标
//        if (StringUtils.isNotBlank(orgId)) {
//            String deptId = orgId;
//            // 查询子单位
//            List<Dept> deptList = iSysClient.getDeptChild(Long.valueOf(deptId)).getData();
//            List<String> deptIdList = new LinkedList<>();
//            if (deptList != null) {
//                deptIdList.addAll(deptList.stream().map(dept -> {
//                    return String.valueOf(dept.getId());
//                }).collect(Collectors.toList()));
//            }
//            deptIdList.add(deptId);
//
//            // 只保留责任单位是自己单位及单位的指标
//            idtDirList = idtDirList.stream().filter(idtDir -> {
//                if (idtDir.getType() == 2) {
//                    if (StringUtils.isNotBlank(idtDir.getIdtDutyCompany())) {
//                        Optional<String> any = deptIdList.stream().filter(childDeptId -> idtDir.getIdtDutyCompany().contains(String.valueOf(childDeptId))).findAny();
//                        return any.isPresent();
//                    }
//                    return false;
//                }
//                return true;
//            }).collect(Collectors.toList());
//        }
        return idtDirList;
    }


    @Override
    public Integer selectMaxSort() {
        return idtIndicatorsDirMapper.selectMaxSort();
    }

    @Override
    public void deleteByIds(String id) {
        idtIndicatorsDirMapper.deleteByIds(id);
    }

    @Override
    public void deleteByParentId(String id) {
        idtIndicatorsDirMapper.deleteByParentId(id);
    }

    @Override
    public List<IdtIndicatorsDir> getAllByParentId(String parentId, String orgId) {
        return idtIndicatorsDirMapper.getAllByParentId(parentId, orgId);
    }

    @Override
    public List<ApiIdtIndicatorsDir> listDirByCode(String parentId, String orgId, String keyWord) {
        return idtIndicatorsDirMapper.listDirByCode(parentId, orgId, keyWord);
    }

    @Override
    public List<String> findById(String id) {
        return idtIndicatorsDirMapper.findById(id);
    }

    /**
     * @描述: 重写评估数值查询接口，减少数据库查询，提高查询效率
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/13 16:50
     */
    @Override
    public void formatApiIndicatorsValList(List<ApiIdtIndicatorsDir> treeList, String year, String areaCode) {
        List<String> idtIds = new ArrayList<>();
        // 重写代码，提供查询速度
        for (ApiIdtIndicatorsDir idtDir : treeList) {
            if (idtDir.getType() == 2) {
                idtIds.add(idtDir.getIndicatorsId());
            }
        }
        if (idtIds.isEmpty()) {
            return;
        }

        List<String> idtIdList = treeList.stream().filter(idt -> {
            return idt.getType() == 2;
        }).map(ApiIdtIndicatorsDir::getIndicatorsId).collect(Collectors.toList());

        Map<String, List<ApiIndicatorsVal>> mapIdtVal = this.iIdtIndicatorsService.mapIdtVal(idtIdList, year, areaCode, false, true);
        for (ApiIdtIndicatorsDir idtDir : treeList) {
            if (idtDir.getType() == 2) {
                List<ApiIndicatorsVal> apiIndicatorsValList = mapIdtVal.get(idtDir.getIndicatorsId());
                apiIndicatorsValList = apiIndicatorsValList.stream().sorted((o1, o2) -> {
                    return o1.getQueryTime().compareTo(o2.getQueryTime());
                }).collect(Collectors.toList());
                idtDir.setApiIndicatorsValList(apiIndicatorsValList);
            }
        }
    }


    @Override
    public JSONArray getIndexFactorGrowthRate(String name, String divisionCode) {
        List<IdtIndicatorsDir> dirList = idtIndicatorsDirMapper.getGrowthRateByName(name);
        JSONArray res = new JSONArray();
        for (IdtIndicatorsDir dir : dirList) {
            List<ApiIndicatorsGrowthRate> list = iIdtMonitorValueService.computeYearGrowthRateByIndicatorsAndDivision(dir.getIndicatorsId(), divisionCode);
            List<Integer> yearList = new ArrayList<>();
            List<Double> growthRatioList = new ArrayList<>();
            for (ApiIndicatorsGrowthRate a : list) {
                yearList.add(a.getYear());
                growthRatioList.add(a.getGrowthRatio());
            }
            if (growthRatioList.size() > 0) {
                JSONObject object = new JSONObject();
                object.put("name", dir.getName());
                JSONObject xAxis = new JSONObject();
                xAxis.put("type", "category");
                xAxis.put("boundaryGap", false);
                xAxis.put("data", yearList);
                object.put("xAxis", xAxis);
                JSONObject yAxis = new JSONObject();
                yAxis.put("type", "value");
                JSONObject axisLabel = new JSONObject();
                axisLabel.put("formatter", "{value}");
                yAxis.put("axisLabel", axisLabel);
                object.put("yAxis", yAxis);
                JSONObject series = new JSONObject();
                series.put("type", "line");
                series.put("data", growthRatioList);
                object.put("series", series);
                res.add(object);
            }
        }
        return res;
    }

    @Override
    public String getDirIdByTypeCode(String typeCode, String divisionCode, List<String> years) {
        String yearStr = String.join(",", years);
        IdtIndicatorsType one = iIdtIndicatorsTypeService.accurateGet(typeCode, yearStr, divisionCode);
        if (Objects.nonNull(one) && org.apache.commons.lang3.StringUtils.isNotBlank(one.getId())) {
            return one.getId();
        }
        return "";
    }

    @Override
    public List<ApiIdtIndicatorsDir> listAllById(String id, String areaCode, String year) {
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = listDirByCode(id, null, null);

        //idtIndicatorsDirService.formatApiIndicatorsValList(treeList, year, areaCode);
        //创建树形结构
        //List<ApiIdtIndicatorsDir> tree = createTree(id, treeList);
        return CollectionUtils.isEmpty(treeList) ? Collections.emptyList() : treeList;
    }

    @Override
    public Map<String, IdtIndicators> mapCode2IdtIndicators() {
        List<IdtIndicators> list = iIdtIndicatorsService.list();
        Map<String, IdtIndicators> collect = list.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e, (e1, e2) -> e2));
        return collect;
    }

    @Override
    public Map<String, String> mapIndicatorsName2Code(List<String> indicatorsNames) {
        if (CollectionUtils.isEmpty(indicatorsNames)) {
            return Collections.emptyMap();
        }
        LambdaQueryWrapper<IdtIndicators> condition = new QueryWrapper().lambda();
        condition.select(IdtIndicators::getName, IdtIndicators::getCode);
        condition.in(IdtIndicators::getName, indicatorsNames);
        List<IdtIndicators> list = iIdtIndicatorsService.list(condition);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(e -> e.getName(), e -> e.getCode(), (e1, e2) -> e2));
        return collect;
    }

    @Override
    public Map<String, IdtIndicators> mapIndicatorsId2Entity(List<String> indicatorsIds) {
        if (CollectionUtils.isEmpty(indicatorsIds)) {
            return Collections.emptyMap();
        }

        LambdaQueryWrapper<IdtIndicators> condition = new QueryWrapper().lambda();
        condition.in(IdtIndicators::getId, indicatorsIds);
        List<IdtIndicators> list = iIdtIndicatorsService.list(condition);

        Map<String, IdtIndicators> collect = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e, (e1, e2) -> e2));
        return collect;
    }

    @Override
    public Map<String, String> mapIndicatorsId2Name(String[] indicatorsIds) {
        if (indicatorsIds == null || indicatorsIds.length <= 0) {
            return Collections.emptyMap();
        }
        LambdaQueryWrapper<IdtIndicators> condition = new QueryWrapper().lambda();
        condition.select(IdtIndicators::getId, IdtIndicators::getName);
        condition.in(IdtIndicators::getId, indicatorsIds);
        List<IdtIndicators> list = iIdtIndicatorsService.list(condition);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getName(), (e1, e2) -> e2));
        return collect;
    }

    @Override
    public Map<String, String> mapIndicatorsId2Unit(String[] indicatorsIds) {
        if (indicatorsIds == null || indicatorsIds.length <= 0) {
            return Collections.emptyMap();
        }
        LambdaQueryWrapper<IdtIndicators> condition = new QueryWrapper().lambda();
        condition.select(IdtIndicators::getId, IdtIndicators::getUnit);
        condition.in(IdtIndicators::getId, indicatorsIds);
        List<IdtIndicators> list = iIdtIndicatorsService.list(condition);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getUnit(), (e1, e2) -> e2));
        return collect;
    }


    @Override
    public List idtListByCodeAndYear(String code, String divisionCode, String year) {
        Map<String, List<ApiIdtIndicatorsDir>> divisionToDir = getDivisionToDir(code, divisionCode, year);

        //行政区划
        List<MapDivision> divisionList = idtIndicatorsDirMapper.getDivisionByParentcode(divisionCode);
        Map<String, String> divisionMap = divisionList.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e.getName(), (e1, e2) -> e2));

        List resultList = new ArrayList();
        for (String xzqh : divisionToDir.keySet()) {
            Map map = new HashMap();
            map.put("divisionCode", xzqh);
            map.put("divisionName", divisionMap.getOrDefault(xzqh, ""));
            List<ApiIdtIndicatorsDir> treeList = divisionToDir.get(xzqh);

            // 获取所有指标
            List<String> idtIdList = treeList.stream().filter(idtDir -> {
                return idtDir.getType() == 2;
            }).map(ApiIdtIndicatorsDir::getIndicatorsId).collect(Collectors.toList());

            Map<String, List<ApiIndicatorsVal>> idtValMap = iIdtIndicatorsService.mapIdtVal(idtIdList, year, xzqh, false, false);
            List<ApiIndicatorsVal> warnValList = new ArrayList<>();
            for (ApiIdtIndicatorsDir dir : treeList) {
                if (dir.getType() == 2) {
                    List<ApiIndicatorsVal> apiIndicatorsValList = idtValMap.get(dir.getIndicatorsId());
                    ApiIndicatorsVal val = apiIndicatorsValList.get(0);
                    if (StringUtils.isNotBlank(val.getWarnRuleConfig())) {
                        String warnStatus = iIdtIndicatorsService.updateWarnStatus(val);
                        val.setWarnStatus(warnStatus);
                        if (val.getWarnStatus().contains("预警")) {
                            warnValList.add(val);
                        }
                    }
                }
            }
            if (CollectionUtils.isEmpty(warnValList)) {
                map.put("value", idtIdList.size());
                map.put("status", "正常");
            } else {
                map.put("value", warnValList.size());
                map.put("status", "预警");
            }
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<IdtIndicators> getRuleByCode(String code, List<String> idtIds, String year, String divisionCode) {
        LambdaQueryWrapper<IdtIndicators> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(IdtIndicators::getId, idtIds);
        List<IdtIndicators> indicatorsList = iIdtIndicatorsService.list(queryWrapper1);
        code = StringUtils.isEmpty(code) ? MONITOR_WARNING_CODE : code;
        //找到对应指标体系
        IdtIndicatorsType indicatorsType = null;
        List<IdtIndicatorsType> idtIndicatorsTypeList = idtIndicatorsTypeMapper.findByCode(code, year, divisionCode);
        for (IdtIndicatorsType idtIndicatorsType : idtIndicatorsTypeList) {
            List<String> divisionCodes = Func.toStrList(idtIndicatorsType.getDivisionCode());
            if (divisionCodes.contains(divisionCode)) {
                indicatorsType = idtIndicatorsType;
            }
        }
        //如果未配置指标体系，则读取指标的规则
        List<IdtIndicators> result = new ArrayList<>();
        for (IdtIndicators idtIndicators : indicatorsList) {
            if (indicatorsType != null) {
                //查找对应指标目录
                IdtIndicatorsDir indicatorsDir = idtIndicatorsDirMapper.getOneByParentId(idtIndicators.getId(), indicatorsType.getId(), null);
                if (indicatorsDir != null) {
                    //目录有配置，采用目录配置
                    if (!StringUtils.isEmpty(indicatorsDir.getWarnRuleConfig())) {
                        idtIndicators.setWarnRuleConfig(indicatorsDir.getWarnRuleConfig());
                    }
                    if (!StringUtils.isEmpty(indicatorsDir.getEstimateRuleConfig())) {
                        idtIndicators.setEstimateRuleConfig(indicatorsDir.getEstimateRuleConfig());
                    }
                }
            }
            result.add(idtIndicators);
        }
        return result;
    }

    //行政区对应的指标体系
    private Map getDivisionToDir(String code, String divisionCode, String year) {
        Map resultMap = new HashMap();
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, year, divisionCode);
        List<String> codes = Arrays.asList(one.getDivisionCode().split(","));
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = this.listDirByCode(one.getId(), null, null);
        //行政区划
        List<MapDivision> divisionList = idtIndicatorsDirMapper.getDivisionByParentcode(divisionCode);
        for (MapDivision map : divisionList) {
            String mapCode = map.getCode();
            if (StringUtils.isEmpty(mapCode)) {
                continue;
            }
            if (codes.contains(mapCode)) {
                resultMap.put(mapCode, treeList);
            } else {
                IdtIndicatorsType type = iIdtIndicatorsTypeService.findByCode(code, year, mapCode);
                List<ApiIdtIndicatorsDir> typeList = this.listDirByCode(type.getId(), null, null);
                resultMap.put(mapCode, typeList);
            }
        }
        return resultMap;
    }


    @Override
    public Map warnListByCode(String code, String divisionCode, String year, String type) {
        Map map = new HashMap();

        //行政区划
        List<MapDivision> divisionList = idtIndicatorsDirMapper.getDivisionByParentcode(divisionCode);

        //各个行政区的指标体系
        List<ApiIndicatorsVal> resultList = new ArrayList<>();

        List<ApiIdtIndicatorsDir> dirs = new ArrayList<>();
        List<String> idtIds = new ArrayList<>();
        Map<MapDivision, IdtIndicatorsType> idtIndicatorsTypeMap = new HashMap<>();

        for (MapDivision mapDivision : divisionList) {
            //获取根据编码获取体系类型
            IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, year, mapDivision.getCode());
            idtIndicatorsTypeMap.put(mapDivision, one);
        }
        List<ApiIndicatorsVal> idtVals = new ArrayList<>();
        for (Map.Entry<MapDivision, IdtIndicatorsType> mapDivisionIdtIndicatorsTypeEntry : idtIndicatorsTypeMap.entrySet()) {
            IdtIndicatorsType idtIndicatorsType = mapDivisionIdtIndicatorsTypeEntry.getValue();
            MapDivision mapDivision = mapDivisionIdtIndicatorsTypeEntry.getKey();
            //获取父节点下的所有数据
            List<ApiIdtIndicatorsDir> treeList = this.listDirByCode(idtIndicatorsType.getId(), null, null);
            if (!CollectionUtils.isEmpty(treeList)) {
                List<ApiIndicatorsVal> idtVal = iIdtIndicatorsService.mapIdtVal3(treeList, year, mapDivision, dirs, idtIds);
                if (CollectionUtil.isNotEmpty(idtVal)) {
                    idtVals.addAll(idtVal);
                }
            }
        }

        if (CollectionUtil.isNotEmpty(idtVals)) {
            long start = System.currentTimeMillis();
            for (ApiIndicatorsVal val : idtVals) {
                if (StringUtils.isNotBlank(val.getWarnRuleConfig())) {
                    String warnStatus = iIdtIndicatorsService.updateWarnStatus(val);
                    val.setWarnStatus(warnStatus);
                    if (val.getWarnStatus().contains("预警")) {
                        resultList.add(val);
                    }
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("用时：" + (end - start) + " ms");
        }

        //指标维度
        if ("0".equals(type)) {
            //指标列表
            Map<String, ApiIdtIndicatorsDir> idtList = dirs.stream().filter(x -> StringUtils.isNotBlank(x.getIndicatorsId())).collect(Collectors.toMap(e -> e.getIndicatorsId(), e -> e, (e1, e2) -> e2));
            //预警的列表
            Map<String, List<ApiIndicatorsVal>> warnList = resultList.stream().collect(Collectors.groupingBy(ApiIndicatorsVal::getId));

            List<ApiIdtIndicatorsDir> result = new ArrayList<>();
            for (Map.Entry<String, List<ApiIndicatorsVal>> entry : warnList.entrySet()) {
                ApiIdtIndicatorsDir dir = idtList.get(entry.getKey());
                if (dir != null && !CollectionUtils.isEmpty(entry.getValue())) {
                    dir.setWarnValList(entry.getValue());
                    result.add(dir);
                }
            }
            result.sort(Comparator.comparing(ApiIdtIndicatorsDir::getSort));
            List<String> str = result.stream().map(x -> x.getIdtName()).collect(Collectors.toList());
            map.put("condition", str);
            map.put("data", result);
        } else {
            //预警的列表
            Map<String, List<ApiIndicatorsVal>> warnList = resultList.stream().collect(Collectors.groupingBy(ApiIndicatorsVal::getDivisionCode));
            List result = new ArrayList();
            List<String> str = new ArrayList<>();
            for (MapDivision mapDivision : divisionList) {
                List<ApiIndicatorsVal> vals = warnList.get(mapDivision.getCode());
                if (!CollectionUtils.isEmpty(vals)) {
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("name", mapDivision.getName());
                    map1.put("code", mapDivision.getCode());
                    map1.put("warnValList", vals);
                    str.add(mapDivision.getCode());
                    result.add(map1);
                }
            }
            map.put("condition", str);
            map.put("data", result);
        }

        return map;
    }

    @Override
    public List<IdtEstimateResultDto> getEstimateResults(String code, String divisionCode, String year) {
        String divisionText = this.iIdtMonitorValueService.getNameByDivisionCode(divisionCode);
        if (StringUtils.isBlank(code)) {
            code = MONITOR_WARNING_CODE;
        }
        List<IdtEstimateResultDto> results = new ArrayList<>();
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, year, divisionCode);
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = this.listDirByCode(one.getId(), null, null);
        if (!CollectionUtils.isEmpty(treeList)) {
            //先筛选目录
            List<ApiIdtIndicatorsDir> dirs = treeList.stream().filter(d -> d.getType() == 1).collect(Collectors.toList());

            //处理好监测值与状态《指标id，指标值》
            Map<String, ApiIndicatorsVal> valByIds = this.getValByIds(treeList, code, divisionCode, year);

            for (ApiIdtIndicatorsDir dir : dirs) {

                IdtEstimateResultDto resultDto = new IdtEstimateResultDto();
                resultDto.setName(dir.getName());
                String describe = CmeReportIdtDescribeEnum.getDescribeByName(dir.getName()).replaceAll("\\$\\{divisionName\\}", divisionText);
                resultDto.setDescribe(describe);

                //查询该目录下的指标列表
                List<ApiIdtIndicatorsDir> indicatorsDirs = treeList.stream().filter(d -> Objects.equals(dir.getId(), d.getParentId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(indicatorsDirs)) {
                    List<IdtEstimateResultDto.IdtEstimateResultTable> tables = new ArrayList<>();
                    for (ApiIdtIndicatorsDir indicatorsDir : indicatorsDirs) {
                        IdtEstimateResultDto.IdtEstimateResultTable table = new IdtEstimateResultDto.IdtEstimateResultTable();
                        table.setIdtName(indicatorsDir.getIdtName());
                        table.setIdtUnit(indicatorsDir.getIdtUnit());
                        ApiIndicatorsVal val = valByIds.getOrDefault(indicatorsDir.getIndicatorsId(), new ApiIndicatorsVal());
                        table.setEstimateValue(val.getMonitorValue());
                        table.setEstimateStatus(val.getEstimateStatus());
                        String rule = this.covertRule(indicatorsDir.getEstimateRuleConfig(), table.getIdtUnit());
                        table.setEstimateRule(rule);
                        table.setIdtDataSource(indicatorsDir.getIdtCalculateSource());
                        tables.add(table);
                    }
                    describe = describe.replaceAll("\\$\\{idtCount\\}", String.valueOf(tables.size()));
                    resultDto.setDescribe(describe);
                    resultDto.setTables(tables);
                }
                results.add(resultDto);
            }
        }
        return results;
    }

    /**
     * @描述: 规则转换描述
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/25 16:15
     **/
    private String covertRule(String ruleJson, String unit) {
        List<idtEstimateRuleValue> idtEstimateRuleValues = com.alibaba.fastjson.JSONArray.parseArray(ruleJson, idtEstimateRuleValue.class);
        if (CollectionUtils.isEmpty(idtEstimateRuleValues)) {
            return "";
        }
        StringBuffer ruleName = new StringBuffer("");
        for (idtEstimateRuleValue rule : idtEstimateRuleValues) {
            if (rule.getEstimateRule().contains("<=")) {
                String value1 = rule.getEstimateRule().replaceAll("<=", "");
                ruleName.append("低于或等于").append(value1).append(unit).append("评为").append(rule.getEstimateLevel()).append("；");
                continue;
            } else if (rule.getEstimateRule().contains(">=")) {
                String value1 = rule.getEstimateRule().replaceAll(">=", "");
                ruleName.append("高于或等于").append(value1).append(unit).append("评为").append(rule.getEstimateLevel()).append("；");
                continue;
            } else if (rule.getEstimateRule().contains(">")) {
                String value1 = rule.getEstimateRule().replaceAll(">", "");
                ruleName.append("高于").append(value1).append(unit).append("评为").append(rule.getEstimateLevel()).append("；");
                continue;
            } else if (rule.getEstimateRule().contains("<")) {
                String value1 = rule.getEstimateRule().replaceAll("<", "");
                ruleName.append("低于").append(value1).append(unit).append("评为").append(rule.getEstimateLevel()).append("；");
                continue;
            } else if (rule.getEstimateRule().contains("~")) {
                String value1 = rule.getEstimateRule().substring(0, rule.getEstimateRule().indexOf("~"));
                String value2 = rule.getEstimateRule().substring(rule.getEstimateRule().indexOf("~") + 1, rule.getEstimateRule().length());
                ruleName.append(value1).append("-").append(value2).append(unit).append("评为").append(rule.getEstimateLevel()).append("；");
                continue;
            }
        }
        return ruleName.toString();
    }

    /**
     * @描述: 根据指标id获取监测值与评估状态
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/25 16:11
     **/
    private Map<String, ApiIndicatorsVal> getValByIds(List<ApiIdtIndicatorsDir> treeList, String code, String divisionCode, String year) {
        List<String> ids = treeList.stream().map(ApiIdtIndicatorsDir::getIndicatorsId).collect(Collectors.toList());

        LambdaQueryWrapper<IdtMonitorValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtMonitorValue::getDivisionCode, divisionCode);
        wrapper.eq(IdtMonitorValue::getYear, Integer.valueOf(year));
        wrapper.in(IdtMonitorValue::getIndicatorsId, ids);
        wrapper.orderByDesc(IdtMonitorValue::getCreateTime);
        List<IdtMonitorValue> values = this.iIdtMonitorValueService.list(wrapper);
        Map<String, List<IdtMonitorValue>> idToValues = values.stream().collect(Collectors.groupingBy(IdtMonitorValue::getIndicatorsId));

        Map<String, ApiIndicatorsVal> valMap = new HashMap<>();
        for (ApiIdtIndicatorsDir dir : treeList) {
            if (dir.getType() == 2) {
                ApiIndicatorsVal val = new ApiIndicatorsVal();
                val.setId(dir.getIndicatorsId());
                val.setMonitorValue(CollectionUtils.isEmpty(idToValues.get(dir.getIndicatorsId())) ? null : idToValues.get(dir.getIndicatorsId()).get(0).getMonitorValue());
                String status = this.iIdtMonitorValueService.getEstimateStatus(code, dir.getIndicatorsId(), val.getMonitorValue(), year, divisionCode);
                val.setEstimateStatus(status);
                valMap.put(dir.getIndicatorsId(), val);
            }
        }
        return valMap;
    }

    @Override
    public Map<String, ApiIndicatorsVal> idToMapVal(String year, String divisionCode) {
        List<ApiIndicatorsVal> idtVal = new ArrayList<>();
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = this.listDirByCode(one.getId(), null, null);
        if (!CollectionUtils.isEmpty(treeList)) {
            MapDivision mapDivision = this.idtIndicatorsDirMapper.getDivisionByCode(divisionCode);
            idtVal = iIdtIndicatorsService.mapIdtVal3(treeList, year, mapDivision, new ArrayList<>(), new ArrayList<>());
        }
        Map<String, ApiIndicatorsVal> collect = idtVal.stream().collect(Collectors.toMap(e -> e.getId(), e -> e, (e1, e2) -> e2));
        return collect;
    }


}
